package com.tbl.modules.wms.controller.baseinfo;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.common.utils.StringUtils;
import com.tbl.modules.platform.constant.LogActionConstant;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.service.system.LogService;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.util.DeriveExcel;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.constant.EmumConstant;
import com.tbl.modules.wms.entity.baseinfo.Car;
import com.tbl.modules.wms.service.baseinfo.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 行车管理
 * @author 70486
 */
@Controller
@RequestMapping(value = "/car")
public class CarController extends AbstractController {

    /**
     * 行车
     */
    @Autowired
    private CarService carService;
    /**
     * 日志信息
     */
    @Autowired
    private LogService logService;
    /**
     * 角色
     */
    @Autowired
    private RoleService roleService;

    /**
     * 跳转到车辆管理列表页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.car));
        mv.setViewName("techbloom/baseinfo/car/car_list");
        return mv;
    }

    /**
     * 获取行车列表数据
     * @param queryJsonString 查询条件
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(4);
        if (!StringUtils.isEmptyString(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        PageUtils utils = carService.getPageList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("rows", utils.getList());
        map.put("total", utils.getTotalPage() == 0 ? 1 : utils.getTotalPage());
        return map;
    }

    /**
     * 导出行车信息Excel
     * @param request
     * @param response
     */
    @RequestMapping(value = "/materialExcel", method = RequestMethod.POST)
    @ResponseBody
    public void materialExcel(HttpServletRequest request, HttpServletResponse response)  {
        try {
            String sheetName = "行车" + "(" + DateUtils.getDay() + ")";
            response.setHeader("Content-Type", "application/force-download");
            response.setHeader("Content-Type", "application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            response.setHeader("Content-disposition", "attachment;filename=" + new String(sheetName.getBytes("gbk"),
                    "ISO8859-1") + ".xls");

            Map<String, String> mapFields = new LinkedHashMap<>();
            String [] excelIndexArray = request.getParameter("queryExportExcelIndex").split(",");

            if (excelIndexArray.length==1&&"".equals(excelIndexArray[0])){
                mapFields.put("code", "行车编码");
                mapFields.put("name", "行车名称");
                mapFields.put("factoryCode", "厂区编码");
                mapFields.put("factoryName", "厂区名称");
                mapFields.put("warehouseName", "所属仓库");
                mapFields.put("warehouseArea", "仓库区域");
                mapFields.put("tag", "标签号");
                mapFields.put("stateStr", "行车状态");
            }else{
                for (String s : excelIndexArray) {
                    if ("2".equals(s)) {
                        mapFields.put("code", "行车编码");
                    } else if ("3".equals(s)) {
                        mapFields.put("name", "行车名称");
                    } else if ("4".equals(s)) {
                        mapFields.put("factoryCode", "厂区编码");
                    } else if ("5".equals(s)) {
                        mapFields.put("factoryName", "厂区名称");
                    } else if ("6".equals(s)) {
                        mapFields.put("warehouseName", "所属仓库");
                    } else if ("7".equals(s)) {
                        mapFields.put("warehouseArea", "仓库区域");
                    } else if ("8".equals(s)) {
                        mapFields.put("tag", "标签号");
                    } else if ("9".equals(s)) {
                        mapFields.put("stateStr", "行车状态");
                    }
                }
            }

            DeriveExcel.exportExcel(sheetName, carService.getExcelList(request.getParameter("ids"), request.getParameter("queryCode"),
                    request.getParameter("queryFactoryCode"), request.getParameter("queryWarehouse"), null), mapFields, response, "");
            logService.logInsert("行车导出", LogActionConstant.USER_EXPORT, request);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 弹出到行车编辑页面
     * @param id 行车主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toAdd.do")
    @ResponseBody
    public ModelAndView toAdd(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/baseinfo/car/car_edit");
        mv.addObject("edit", id != null && id != EmumConstant.carState.INSTORAGING.getCode().longValue() ?
                EmumConstant.carState.OUTSTORAGING : EmumConstant.carState.INSTORAGING);
        //okk
        mv.addObject("car", carService.findCarById(id, getSessionUser().getFactoryCode()));
        mv.addObject("warehouseAreaList" , carService.selectWarehouseArea());
        return mv;
    }

    /**
     * 获取仓库的下拉选信息
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/selectWarehouse")
    @ResponseBody
    public Map<String, Object> selectWarehouse() {
        Map<String, Object> map = new HashMap<>(5);
        PageTbl page = this.getPage();
        page.setPageno(Integer.parseInt(request.getParameter("pageNo")));
        //okk
        map.put("factoryCodeList", getSessionUser().getFactoryCode()!=null ? Arrays.asList(getSessionUser().getFactoryCode().split(",")) : null);
        map.put("warehouseIds", getSessionUser().getUserFactoryIds()!=null ? Arrays.asList(getSessionUser().getUserFactoryIds().split(",")) : null);
        map.put("factoryId", request.getParameter("factoryCodeId"));
        map.put("queryString", request.getParameter("queryString").toUpperCase());
        PageUtils utils = carService.getPageWarehouseList(page, map);
        page.setTotalRows(utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        //初始化分页对象
        executePageMap(map, page);
        map.put("result", utils.getList());
        map.put("total", utils.getTotalCount() == 0 ? 1 : utils.getTotalCount());
        return map;
    }

    /**
     * 根据主键查询行车
     * @param id 行车主键
     * @return Car 行车
     */
    @RequestMapping(value = "/getCarById")
    @ResponseBody
    public Car getCarById(Long id) {
        //okk
        return carService.findCarById(id,getSessionUser().getFactoryCode());
    }

    /**
     * 保存行车信息
     * @param car 行车
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/saveCar")
    @ResponseBody
    public Map<String, Object> saveCar(Car car) {
        Map<String, Object> map = new HashMap<>(2);
        car.setWarehouseArea(car.getWarehouseArea().replaceAll("\\d+",""));
        boolean result = carService.saveCar(car);
        map.put("result", result);
        map.put("msg",result ? "保存成功！" : "保存失败！");
        return map;
    }

    /**
     * 删除行车信息
     * @param ids 行车主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/deleteCars.do")
    @ResponseBody
    public Map<String, Object> deleteCars(String ids) {
        Map<String, Object> map = new HashMap<>(2);
        boolean result = carService.deleteCars(ids);
        map.put("result", result);
        map.put("msg", result?"删除成功！":"删除失败！");
        return map;
    }

    /**
     * 判断行车编码是否已存在
     * @param code 行车编码
     * @param id 行车主键
     * @return boolean
     */
    @RequestMapping(value = "/existsCarCode")
    @ResponseBody
    public boolean existsCarCode(String code, Long id) {
        code = code.split(",")[1];
        Car car = null;
        if (!StringUtils.isEmptyString(code)) {
            car = carService.findCarByCode(code);
        }
        if (id == null) {
            return car == null;
        } else {
            return car == null || id.equals(car.getId());
        }
    }
    
    /**
     * 启用
     * @param ids
     */
    @RequestMapping(value = "/isStart.do")
    @ResponseBody
    public void isStart(Long[] ids) {
        Car carEntity = new Car();
        carEntity.setState(Constant.LONG_TWO);
        carService.update(carEntity, new EntityWrapper<Car>().in("ID", ids));
    }
    
    /**
     * 出库中
     * @param ids
     */
    @RequestMapping(value = "/outMiss.do")
    @ResponseBody
    public void outMiss( Long[] ids) {
        Car carEntity = new Car();
        carEntity.setState(Constant.LONG_ONE);
        carService.update(carEntity, new EntityWrapper<Car>().in("ID", ids));
    }

    /**
     * 入库中
     * @param ids
     */
    @RequestMapping(value = "/inMiss.do")
    @ResponseBody
    public void inMiss(Long[] ids) {
        Car carEntity = new Car();
        carEntity.setState(Constant.LONG_ZERO);
        carService.update(carEntity, new EntityWrapper<Car>().in("ID", ids));
    }

    /**
     * 获取行车的仓库区域
     * @param id 行车主键
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/findCarWarehouseAreaList.do")
    @ResponseBody
    public List<Map<String, Object>> findCarWarehouseAreaList(Long id) {
        return carService.selectWarehouseArea();
    }

}
